import Taro from '@tarojs/taro';
import {
  getCityListApi,
  getConversionApi,
  uploadBase64ToAliApi,
  uploadUFileApi,
} from '../api/commonApi';
import { QQ_MAP_KEY } from '@/config/env';

//上传base64版本到阿里云服务器上
export const uploadFileToAliFun = (file: any) => {
  return new Promise((reslve: any, reject: any) => {
    // 上传base64格式
    uploadBase64ToAliApi(file)
      .then((res: any) => {
        if (res.data && res.data.data && res.data.data.fileUrl) {
          reslve(res.data.data.fileUrl);
        } else {
          reject(res);
        }
      })
      .catch((e: any) => {
        reject(e);
      });
  });
};

export const getBase64File = async (filePath: any) => {
  const fs = Taro.getFileSystemManager();
  const base64: string = await new Promise((resolve, reject) => {
    fs.readFile({
      filePath,
      encoding: 'base64',
      success: (r) => {
        resolve(`data:image/jpeg;base64,${r.data}`);
      },
      fail: (err) => reject(err),
    });
  });
  return base64;
};

//城市列表
export const getCityListFun = async (data: any = {}) => {
  return new Promise((reslve: any, reject: any) => {
    getCityListApi(data)
      .then((res: any) => {
        reslve(res.data);
      })
      .catch((e: any) => {
        reject(e);
      });
  });
};

// 经纬度转化成省市区调用腾讯的服务结合本地缓存的城市列表获取code值
export const getConversionFun = async (location: string = '') => {
  const params = {
    location,
    key: QQ_MAP_KEY,
    get_poi: 1,
  };
  return new Promise((reslve: any, reject: any) => {
    getConversionApi(params)
      .then((res: any) => {
        const cityList = Taro.getStorageSync('cityList');
        const comp = res.result.address_component;
        const provName = comp.province;
        const cityName = comp.city;
        if (!Array.isArray(cityList) || cityList.length === 0) {
          throw new Error('本地 cityList 为空，请先缓存完整列表');
        }
        // 3. 匹配省
        const prov = cityList.find((p: any) => p.areaName === provName);
        if (!prov) {
          throw new Error(`未在缓存中找到省：${provName}`);
        }
        // 4. 匹配市
        const city = (prov.children || []).find(
          (c: any) => c.areaName === cityName
        );
        if (!city) {
          throw new Error(`未在 ${provName} 下找到市：${cityName}`);
        }
        const data = {
          province: { areaCode: prov.areaCode, areaName: prov.areaName },
          city: { areaCode: city.areaCode, areaName: city.areaName },
        };
        reslve(data);
      })
      .catch((e: any) => {
        reject(e);
      });
  });
};

// 将市转化成经纬度
export const convertCityToLALFun = async (cityName: string = '') => {
  const params = {
    address: cityName,
    key: QQ_MAP_KEY,
  };
  return new Promise((reslve: any, reject: any) => {
    getConversionApi(params)
      .then((res: any) => {
        if (res.status === 0) {
          console.log(res, '返回内容getConversionApi');
          const { lat, lng } = res.result.location;
          const data = { latitude: lat, longitude: lng };
          reslve(data);
        } else {
          // Taro.showToast({ title: '返回失败', icon: 'none' });
          console.error(res, '返回内容getConversionApi失败');
        }
      })
      .catch((e: any) => {
        reject(e);
      });
  });
};

/** 上传单张图片 */
export const uploadUhomeFileFun = (
  filePath: string,
  name: string,
  extra: any
) => {
  return uploadUFileApi(filePath, name, extra);
};

// 格式化时间
export const formatNow = (date = new Date()) => {
  const pad = (n: number) => String(n).padStart(2, '0');
  const y = date.getFullYear();
  const M = pad(date.getMonth() + 1);
  const d = pad(date.getDate());
  const h = pad(date.getHours());
  const m = pad(date.getMinutes());
  const s = pad(date.getSeconds());
  return `${y}-${M}-${d} ${h}:${m}:${s}`;
};

//判断用户是否登录
export const isLoginFun = () => {
  //1.判断用户是否登录
  if (
    Taro.getStorageSync('access_token_login') === '' ||
    Taro.getStorageSync('userId') === ''
  ) {
    Taro.showToast({ title: '请先登录', icon: 'none' });
    setTimeout(() => {
      Taro.navigateTo({ url: '/subPagesAuth/login/index' });
    }, 2000);
    return false;
  }
  return true;
};

export const safeBack = (delta = 1, fallback?: () => void) => {
  const pages = Taro.getCurrentPages?.() || [];
  if (pages.length > delta) {
    Taro.navigateBack({ delta });
  } else {
    // 兜底：没有足够的历史
    if (fallback) return fallback();
    // 兜底：回首页 tab
    Taro.switchTab({ url: '/pages/home/index' });
  }
};
